package com.mayihr.new_learn_fx.UIControl.treeviewsample;

import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.cell.CheckBoxTreeCell;
import javafx.scene.input.KeyCode;

public class CheckBoxTreeCellImpl extends CheckBoxTreeCell {
    private TextField textField;
//    private ContextMenu addMenu=new ContextMenu();

    public CheckBoxTreeCellImpl() {
//        MenuItem addMenuItem = new MenuItem("Add Employee");
//        addMenu.getItems().add(addMenuItem);
//        addMenuItem.setOnAction(event -> {
//            TreeItem newItem = new TreeItem("new Item");
//            getTreeItem().getChildren().add(newItem);
//        });
    }

    @Override
    public void startEdit() {
        super.startEdit();
        if (textField == null) {
            createTextFiled();
        }
        setText(null);
        setGraphic(textField);
        textField.selectAll();

    }

    @Override
    public void cancelEdit() {
        super.cancelEdit();
        setText(getString());
        setGraphic(getTreeItem().getGraphic());
    }

    @Override
    public void updateItem(Object item, boolean empty) {
        super.updateItem(item, empty);

        if (empty) {
            setText(null);
            setGraphic(null);
        }else {
            if (isEditing()) {
                if (textField!=null){
                    textField.setText(getString());
                }
                setText(null);
                setGraphic(textField);
            }else{
                setText(getString());
                setGraphic(getTreeItem().getGraphic());
//                if (!getTreeItem().isLeaf()&&getTreeItem().getParent()!= null){
//                        setContextMenu(addMenu);
//                    }
            }
        }
    }

    private void createTextFiled() {
        textField = new TextField(getString());
        textField.setOnKeyReleased(e -> {
            if (e.getCode()==KeyCode.ENTER){
                commitEdit(textField.getText());
            }else if(e.getCode()==KeyCode.ESCAPE){
                cancelEdit();
            }
        });
    }

    private String getString() {
        return getItem() == null ? "" : getItem().toString();
    }
}
